import fs from "node:fs";
import readline from "readline";
import CryptoJS from "crypto-js";

const activityPath = "pages/Doc/activity";
const activityDataPath = "pages/Data/activity.json";
const newsPath = "pages/Doc/news";
const newsDataPath = "pages/Data/news.json";

// 获取活动数据
fs.readdir(activityPath, async (err, files) => {
  if (err) throw err;
  const activityData = await getData(files, activityPath);
  fs.writeFileSync(activityDataPath, JSON.stringify(activityData));
});

// 获取文章数据
fs.readdir(newsPath, async (err, files) => {
  if (err) throw err;
  const newsData = {};
  for await (const file of files) {
    try {
      const newsFiles = fs.readdirSync(`${newsPath}/${file}`);
      newsData[file] = await getData(newsFiles, `${newsPath}/${file}`);
    } catch {}
  }
  fs.writeFileSync(newsDataPath, JSON.stringify(newsData));
});

// 获取某个文件数据
const getData = async (files, path) => {
  const data = [];
  for await (const file of files) {
    const key = await getKeyData(file, path);
    const id = CryptoJS.MD5(`${path}/${file}`).toString();
    data.push({
      id,
      path: `${path}/${file}`,
      ...key,
    });
  }
  return data;
};

// 获取md文件里面的信息
const getKeyData = async (file, path) => {
  const keyValue = {};
  const readStream = fs.createReadStream(`${path}/${file}`);
  const rl = readline.createInterface({
    input: readStream,
    crlfDelay: Infinity,
  });
  let isStart = false;
  for await (const line of rl) {
    if (line === "---") {
      if (isStart) {
        isStart = false;
        rl.close();
      } else {
        isStart = true;
      }
    } else if (isStart && line) {
      try {
        const [content, key, value] = line.match(/^(\w+)[:：](.*)$/);
        keyValue[key] = value;
      } catch {}
    }
  }
  return keyValue;
};
